// 电机档案运行数据管理相关的JavaScript代码
let ARCHIVESOPERATION_API_BASE = '/api/feibiao/operation';
let currentArchivesPage = 0;
let archivesPageSize = 10;
let currentArchivesSearchKeyword = '';

// 当DOM加载完成后检查全局API基础路径并相应地设置
document.addEventListener('DOMContentLoaded', function() {
    // 如果存在全局API基础路径，使用它
    if (typeof API_BASE !== 'undefined') {
        ARCHIVESOPERATION_API_BASE = `${API_BASE}/feibiao/operation`;
    }
});

// 加载电机档案运行数据列表
function loadArchivesOperationList(page = 0, size = 10) {
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 保存当前页码
    currentArchivesPage = page;
    archivesPageSize = size;
    
    fetch(`${ARCHIVESOPERATION_API_BASE}?page=${page}&size=${size}`)
        .then(response => {
            if (!response.ok) {
                return response.text().then(text => {
                    console.error('API请求失败:', response.status, response.statusText, text);
                    try {
                        const error = JSON.parse(text);
                        throw new Error(`服务器错误 (${response.status}): ${error.message || error.error || response.statusText}`);
                    } catch (e) {
                        if (e instanceof SyntaxError) {
                            throw new Error(`服务器错误 (${response.status}): ${text || response.statusText}`);
                        }
                        throw e;
                    }
                });
            }
            return response.json();
        })
        .then(data => {
            renderArchivesOperationTable(data);
        })
        .catch(error => {
            console.error('获取电机档案运行数据失败:', error);
            mainContent.innerHTML = `
                <div class="error-container">
                    <h2>加载数据失败</h2>
                    <p>错误信息: ${error.message}</p>
                    <div class="error-actions">
                        <button class="btn btn-primary" onclick="loadArchivesOperationList()">重试</button>
                    </div>
                </div>
            `;
            showMessage('获取电机档案运行数据失败: ' + error.message, 'error');
        });
}

// 渲染电机档案运行数据表格
function renderArchivesOperationTable(data) {
    const mainContent = document.getElementById('mainContent');
    let html = `
        <div class="content-header">
            <h2 class="content-title">电机档案运行数据管理</h2>
            <div class="header-actions">
                <button class="btn btn-primary" onclick="showArchivesOperationForm()"></i> 新增</button>
            </div>
        </div>
        <div class="content-toolbar">
            <div class="search-box">
                <input type="text" class="search-input" id="archivesOperationSearchInput" placeholder="输入电机ID搜索..." value="${currentArchivesSearchKeyword}">
                <button class="search-btn" onclick="searchArchivesOperation()">搜索</button>
                ${currentArchivesSearchKeyword ? '<button class="btn btn-default" onclick="clearArchivesSearch()">返回列表</button>' : ''}
            </div>
        </div>
        <div class="table-responsive">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>电机ID</th>
                        <th>运行时间</th>
                        <th>电流(A)</th>
                        <th>电压(V)</th>
                        <th>温度(℃)</th>
                        <th>转速(rpm)</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
    `;

    if (data.content && data.content.length > 0) {
        data.content.forEach(operation => {
            html += `
                <tr>
                    <td>${operation.operationId}</td>
                    <td>${operation.motorId}</td>
                    <td>${formatDateTime(operation.operationTime)}</td>
                    <td>${operation.current || '-'}</td>
                    <td>${operation.voltage || '-'}</td>
                    <td>${operation.temperature || '-'}</td>
                    <td>${operation.rotationSpeed || '-'}</td>
                    <td class="table-actions">
                        <a href="javascript:void(0)" onclick="viewArchivesOperation(${operation.operationId})">查看</a>
                        <a href="javascript:void(0)" onclick="editArchivesOperation(${operation.operationId})">编辑</a>
                        <a href="javascript:void(0)" class="delete" onclick="deleteArchivesOperation(${operation.operationId})">删除</a>
                    </td>
                </tr>
            `;
        });
    } else {
        html += `
            <tr>
                <td colspan="8" class="text-center">暂无数据</td>
            </tr>
        `;
    }

    html += `
                </tbody>
            </table>
        </div>
    `;

    // 添加分页控件 - 改为与failure.js相同的样式
    if (data.totalPages > 0) {
        html += `
            <ul class="pagination">
                <li class="${currentArchivesPage <= 0 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${currentArchivesPage <= 0 ? 'void(0)' : 'loadArchivesOperationList(' + (currentArchivesPage - 1) + ', ' + archivesPageSize + ')'}">上一页</a>
                </li>
        `;
        
        // 页码
        for (let i = 0; i < data.totalPages; i++) {
            if (i === currentArchivesPage) {
                html += `<li class="active"><a href="javascript:void(0)">${i + 1}</a></li>`;
            } else {
                html += `<li><a href="javascript:void(0)" onclick="loadArchivesOperationList(${i}, ${archivesPageSize})">${i + 1}</a></li>`;
            }
        }
        
        html += `
                <li class="${currentArchivesPage >= data.totalPages - 1 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${currentArchivesPage >= data.totalPages - 1 ? 'void(0)' : 'loadArchivesOperationList(' + (currentArchivesPage + 1) + ', ' + archivesPageSize + ')'}">下一页</a>
                </li>
            </ul>
        `;
    }

    mainContent.innerHTML = html;
}

// 显示电机档案运行数据表单
function showArchivesOperationForm(operation = null) {
    const mainContent = document.getElementById('mainContent');
    const isEdit = operation !== null;

    mainContent.innerHTML = `
        <div class="content-header">
            <h2 class="content-title">${isEdit ? '编辑' : '新增'}电机档案运行数据</h2>
            <div class="header-actions">
                <button class="btn btn-default" onclick="loadArchivesOperationList(${currentArchivesPage}, ${archivesPageSize})">返回列表</button>
            </div>
        </div>
        <div class="form-container">
            <form id="archivesOperationForm" onsubmit="return submitArchivesOperationForm(event)">
                ${isEdit ? `<input type="hidden" id="operationId" value="${operation.operationId}">` : ''}
                <div class="form-group">
                    <label for="motorId">电机ID:</label>
                    <input type="text" id="motorId" name="motorId" class="form-control" required
                           value="${isEdit ? operation.motorId : ''}">
                </div>
                <div class="form-group">
                    <label for="operationTime">运行时间:</label>
                    <input type="datetime-local" id="operationTime" name="operationTime" class="form-control" required
                           value="${isEdit ? formatDateTimeForInput(operation.operationTime) : ''}">
                </div>
                <div class="form-group">
                    <label for="current">电流(A):</label>
                    <input type="number" id="current" name="current" class="form-control" step="0.01"
                           value="${isEdit ? operation.current : ''}">
                </div>
                <div class="form-group">
                    <label for="voltage">电压(V):</label>
                    <input type="number" id="voltage" name="voltage" class="form-control" step="0.01"
                           value="${isEdit ? operation.voltage : ''}">
                </div>
                <div class="form-group">
                    <label for="temperature">温度(℃):</label>
                    <input type="number" id="temperature" name="temperature" class="form-control" step="0.01"
                           value="${isEdit ? operation.temperature : ''}">
                </div>
                <div class="form-group">
                    <label for="rotationSpeed">转速(rpm):</label>
                    <input type="number" id="rotationSpeed" name="rotationSpeed" class="form-control" step="0.01"
                           value="${isEdit ? operation.rotationSpeed : ''}">
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">${isEdit ? '更新' : '保存'}</button>
                    <button type="button" class="btn btn-default" onclick="loadArchivesOperationList(${currentArchivesPage}, ${archivesPageSize})">取消</button>
                </div>
            </form>
        </div>
    `;
}

// 查看电机档案运行数据详情
function viewArchivesOperation(id) {
    fetch(`${ARCHIVESOPERATION_API_BASE}/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`服务器错误 (${response.status}): ${response.statusText}`);
            }
            return response.json();
        })
        .then(operation => {
            showArchivesOperationDetail(operation);
        })
        .catch(error => {
            console.error('获取电机档案运行数据详情失败:', error);
            showMessage('获取电机档案运行数据详情失败: ' + error.message, 'error');
        });
}

// 显示电机档案运行数据详情
function showArchivesOperationDetail(operation) {
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = `
        <div class="content-header">
            <h2 class="content-title">电机档案运行数据详情</h2>
            <div class="header-actions">
                <button class="btn btn-default" onclick="loadArchivesOperationList(${currentArchivesPage}, ${archivesPageSize})"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
        <div class="data-detail">
            <div class="detail-group"><label>ID:</label><div>${operation.operationId || '--'}</div></div>
            <div class="detail-group"><label>电机ID:</label><div>${operation.motorId || '--'}</div></div>
            <div class="detail-group"><label>运行时间:</label><div>${formatDateTime(operation.operationTime) || '--'}</div></div>
            <div class="detail-group"><label>电流(A):</label><div>${operation.current || '--'}</div></div>
            <div class="detail-group"><label>电压(V):</label><div>${operation.voltage || '--'}</div></div>
            <div class="detail-group"><label>温度(℃):</label><div>${operation.temperature || '--'}</div></div>
            <div class="detail-group"><label>转速(rpm):</label><div>${operation.rotationSpeed || '--'}</div></div>
            <div class="detail-group"><label>运行日期:</label><div>${formatDateTime(operation.operationDate) || '--'}</div></div>
            <div class="detail-actions">
                <button class="btn btn-primary" onclick="editArchivesOperation(${operation.operationId})"><i class="fa fa-edit"></i> 编辑</button>
                <button class="btn btn-danger" onclick="deleteArchivesOperation(${operation.operationId})"><i class="fa fa-trash"></i> 删除</button>
                <button class="btn btn-default" onclick="loadArchivesOperationList(${currentArchivesPage}, ${archivesPageSize})"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
    `;
}

// 提交电机档案运行数据表单
function submitArchivesOperationForm(event) {
    event.preventDefault();
    
    // 获取表单数据
    const motorId = document.getElementById('motorId').value.trim();
    const operationTime = document.getElementById('operationTime').value;
    const current = document.getElementById('current').value;
    const voltage = document.getElementById('voltage').value;
    const temperature = document.getElementById('temperature').value;
    const rotationSpeed = document.getElementById('rotationSpeed').value;
    
    // 数据验证
    if (!motorId) {
        showMessage('请输入电机ID', 'error');
        return false;
    }
    
    if (!operationTime) {
        showMessage('请选择运行时间', 'error');
        return false;
    }
    
    // 验证数值范围
    const validateNumber = (value, fieldName, min, max) => {
        if (value && (isNaN(value) || value < min || value > max)) {
            showMessage(`${fieldName}必须在${min}到${max}之间`, 'error');
            return false;
        }
        return true;
    };
    
    if (!validateNumber(current, '电流', -1000, 1000)) return false;
    if (!validateNumber(voltage, '电压', 0, 1000)) return false;
    if (!validateNumber(temperature, '温度', -50, 200)) return false;
    if (!validateNumber(rotationSpeed, '转速', 0, 10000)) return false;
    
    const formData = {
        motorId: motorId,
        operationTime: operationTime,
        current: current ? parseFloat(current) : null,
        voltage: voltage ? parseFloat(voltage) : null,
        temperature: temperature ? parseFloat(temperature) : null,
        rotationSpeed: rotationSpeed ? parseFloat(rotationSpeed) : null
    };
    
    const operationId = document.getElementById('operationId');
    const isEdit = operationId !== null;
    const url = isEdit ? `${ARCHIVESOPERATION_API_BASE}/${operationId.value}` : ARCHIVESOPERATION_API_BASE;
    const method = isEdit ? 'PUT' : 'POST';
    
    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                throw new Error(`服务器错误 (${response.status}): ${text || response.statusText}`);
            });
        }
        return response.json();
    })
    .then(data => {
        showMessage(`${isEdit ? '更新' : '新增'}电机档案运行数据成功`, 'success');
        loadArchivesOperationList(currentArchivesPage, archivesPageSize);
    })
    .catch(error => {
        console.error(`${isEdit ? '更新' : '新增'}电机档案运行数据失败:`, error);
        showMessage(`${isEdit ? '更新' : '新增'}电机档案运行数据失败: ` + error.message, 'error');
    });
    
    return false;
}

// 编辑电机档案运行数据
function editArchivesOperation(id) {
    fetch(`${ARCHIVESOPERATION_API_BASE}/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`服务器错误 (${response.status}): ${response.statusText}`);
            }
            return response.json();
        })
        .then(operation => {
            showArchivesOperationForm(operation);
        })
        .catch(error => {
            console.error('获取电机档案运行数据详情失败:', error);
            showMessage('获取电机档案运行数据详情失败: ' + error.message, 'error');
        });
}

// 删除电机档案运行数据
function deleteArchivesOperation(id) {
    if (confirm('确定要删除这条电机档案运行数据吗？')) {
        fetch(`${ARCHIVESOPERATION_API_BASE}/${id}`, {
            method: 'DELETE'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`服务器错误 (${response.status}): ${response.statusText}`);
            }
            showMessage('删除电机档案运行数据成功', 'success');
            loadArchivesOperationList(currentArchivesPage, archivesPageSize);
        })
        .catch(error => {
            console.error('删除电机档案运行数据失败:', error);
            showMessage('删除电机档案运行数据失败: ' + error.message, 'error');
        });
    }
}

// 清除搜索
function clearArchivesSearch() {
    document.getElementById('archivesOperationSearchInput').value = '';
    currentArchivesSearchKeyword = '';
    currentArchivesPage = 0;
    loadArchivesOperationList(0, archivesPageSize);
}

// 搜索电机档案运行数据
function searchArchivesOperation() {
    const keyword = document.getElementById('archivesOperationSearchInput').value.trim();
    currentArchivesSearchKeyword = keyword;
    currentArchivesPage = 0;
    
    if (!keyword) {
        loadArchivesOperationList(0, archivesPageSize);
        return;
    }
    
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 直接使用/by-motor端点 - 这是专门为电机ID搜索设计的API
    fetch(`${ARCHIVESOPERATION_API_BASE}/by-motor?motorId=${encodeURIComponent(keyword)}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`搜索失败 (${response.status}): ${response.statusText}`);
            }
            return response.json();
        })
        .then(data => {
            // 处理返回的数据（预期是数组）
            const content = Array.isArray(data) ? data : [];
            
            // 将数据转换为分页格式以便复用现有的表格渲染函数
            const pageData = {
                content: content,
                totalPages: 1,
                number: 0,
                size: content.length,
                first: true,
                last: true,
                totalElements: content.length
            };
            
            // 显示搜索结果
            renderArchivesOperationTable(pageData);
            
            // 显示搜索信息
            const searchInfo = document.createElement('div');
            searchInfo.className = 'search-result-info';
            searchInfo.innerHTML = `搜索"${keyword}": 找到 ${content.length} 条记录`;
            document.querySelector('.content-toolbar').after(searchInfo);
        })
        .catch(error => {
            console.error('搜索电机档案运行数据失败:', error);
            showMessage('搜索电机档案运行数据失败: ' + error.message, 'error');
            
            // 搜索失败时显示空结果
            renderArchivesOperationTable({
                content: [],
                totalPages: 0,
                number: 0,
                size: archivesPageSize,
                first: true,
                last: true,
                totalElements: 0
            });
        });
}

// 格式化日期时间
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '-';
    const date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

// 格式化日期时间为input datetime-local的值
function formatDateTimeForInput(dateTimeStr) {
    if (!dateTimeStr) return '';
    const date = new Date(dateTimeStr);
    return date.toISOString().slice(0, 16);
}

// 将函数暴露给全局
if (typeof window !== 'undefined') {
    window.loadArchivesOperationList = loadArchivesOperationList;
    window.renderArchivesOperationTable = renderArchivesOperationTable;
    window.showArchivesOperationForm = showArchivesOperationForm;
    window.viewArchivesOperation = viewArchivesOperation;
    window.showArchivesOperationDetail = showArchivesOperationDetail;
    window.submitArchivesOperationForm = submitArchivesOperationForm;
    window.editArchivesOperation = editArchivesOperation;
    window.deleteArchivesOperation = deleteArchivesOperation;
    window.searchArchivesOperation = searchArchivesOperation;
    window.clearArchivesSearch = clearArchivesSearch;
} 